import React, { useCallback, useEffect, useMemo } from 'react'
import { WingBlank, NavBar, WhiteSpace, Card, List, Checkbox, Button, Modal } from 'antd-mobile'
import { connect } from 'dva'
import router from 'umi/router'
import classNames from 'classnames'
import { createNamedAction } from 'Local/utils'
import config from 'Local/utils/config'
import BottomNavBar from 'Local/components/nav_action_bar'

import { NAMESPACE } from '../model'
import styles from './index.scss'

const createLocalAction = createNamedAction(NAMESPACE)

let lastProgess = 0

const Index = props => {
  const { dispatch } = props
  const {
    fileName, questions, questionsProgess, questionsScore
  } = props[NAMESPACE]

  const question = useMemo(
    () => {
      const result = questions[questionsProgess] || { options: [] }
      if (!questions.length) {
        return result
      }

      if (!result.title) {
        Modal.alert('错误', '没有这条题目', [
          {
            text: '确定',
            onPress: () => {
              dispatch(createLocalAction('navQuestionHandle')({ current: lastProgess }))
              lastProgess = 0
            }
          }
        ])

        return result
      }

      lastProgess = questionsProgess
      return questions[questionsProgess]
    },
    [fileName, questions, questionsProgess]
  )

  useEffect(() => {
    if (!fileName) {
      requestAnimationFrame(() => router.replace('/'))
    }
  }, [question])

  const navBackHandle = useCallback(() => {
    router.go(-1)
  }, [dispatch])

  const optionSelectHandle = useCallback(option => {
    dispatch(createLocalAction('optionSelectHandle')({
      option,
      question: question.key
    }))
  }, [dispatch, question])

  const cardTitle = useMemo(() => {
    let title = config.MAPS.questionType(question.type)
    // title += ` (${questionsProgess + 1}/${question.sameTypeQuestionsLength})`
    return title
  }, [question])

  const score = useMemo(() => {
    const right = questionsScore.right
    const total = questionsScore.right + questionsScore.wrong
    if (total === 0) {
      return `得分：0/0`
    }
    return `得分：${right}/${total}`
  }, [questionsScore])

  const choosen = useMemo(() => {
    return !!question.options.filter(option => option.selected).length
  }, [question])

  const wantAnswerHandle = useCallback(() => {
    dispatch(createLocalAction('wantAnswerHandle')())
  }, [dispatch])

  const navQuestionHandle = useCallback(current => {
    dispatch(createLocalAction('navQuestionHandle')({ current }))
  }, [dispatch])

  if (!question.title) {
    return null
  }

  return (
    <>
      <NavBar
        mode='light'
        icon='重选'
        onLeftClick={navBackHandle}
      >{fileName}</NavBar>

      {/* 题目详情 */}
      <WingBlank size='lg'>
        <WhiteSpace size='lg' />
        <Card>
          <Card.Header
            title={cardTitle}
            extra={score}
          />
          <Card.Body>
            <div>{question.title}</div>
          </Card.Body>
        </Card>

        {/* 题目选项 */}
        <WhiteSpace size='lg' />
        <List>
          {
            question.options
              .filter(option => !!option.label)
              .map(option => (
                <Checkbox.CheckboxItem
                  multipleLine
                  className={classNames(styles.multilineOption)}
                  key={option.key}
                  checked={option.selected}
                  onChange={() => optionSelectHandle(option.key)}
                >
                  {`${option.key}: ${option.label}`}
                </Checkbox.CheckboxItem>
              ))
          }
        </List>

        {/* 答案 */}
        <WhiteSpace size='lg' />
        <div className={classNames({
          [styles.currentAnswerSection]: true,
          [styles.currentAnswerSectionShow]: choosen
        })}>
          <Card
            className={
              classNames({
                [styles.currentAnswerCardWithBlur]: true,
                [styles.currentAnswerCard]: question.showCorrect
              })
            }
          >
            <Card.Header
              title='正确答案'
            />
            <Card.Body>
              <div>{question.showCorrect ? question.correct : '***'}</div>
            </Card.Body>
          </Card>
          {
            question.remarks ? (
              <>
                <WhiteSpace size='lg' />
                <Card
                  className={
                    classNames({
                      [styles.currentAnswerCardWithBlur]: true,
                      [styles.currentAnswerCard]: question.showCorrect
                    })
                  }
                >
                  <Card.Header
                    title='答案备注'
                  />
                  <Card.Body>
                    <div>{question.showCorrect ? question.remarks : '***'}</div>
                  </Card.Body>
                </Card>
              </>
            ) : null
          }

          <div className={classNames({
            [styles.currentAnswerMask]: true,
            [styles.currentAnswerMaskHide]: question.showCorrect
          })}>
            <Button
              type='primary'
              size='small'
              className={styles.currentAnswerBtn}
              onClick={wantAnswerHandle}
            >查看答案</Button>
          </div>
        </div>
        <WhiteSpace size='lg' />

        {/* 底部操作栏 */}
        <BottomNavBar
          total={questions.length}
          current={questionsProgess}
          onNav={navQuestionHandle}
        />
      </WingBlank>
    </>
  )
}

export default connect(state => ({
  [NAMESPACE]: state[NAMESPACE]
}))(Index)
